package test.com.db.server.requirements.highload;

import com.db.client.ChatPrinter;
import com.db.client.UI;
import com.db.client.UIs.ConsoleFactory;
import com.db.protocol.*;
import com.db.protocol.Command;
import com.db.protocol.Request;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.StringTokenizer;

public class ChatClient extends Thread {

    Stats stats = new Stats();
    private int msecPerMsg;

    public ChatClient(int msecPerMsg) {
        setDaemon(true);
        this.msecPerMsg = msecPerMsg;
    }

    @Override
    public void run() {
        while (!isInterrupted()) {
            try (
                    Socket socket = new Socket("127.0.0.1", 1234);
                    ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
                    ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
            ) {
                register(out, in);
                while (!isInterrupted()) {
                    try {
                        try {
                            sleep(msecPerMsg);
                        } catch (InterruptedException e) {}
                        Object resp;
                        String chars150 ="123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
                        out.writeObject(new Request(Command.snd, new String[]{chars150}));
                        long time = System.currentTimeMillis();
                        while (!((String)in.readObject()).contains(getName())) {}
                        time = System.currentTimeMillis() - time;
                        if (time > 200) {
                            stats.slow();
                            continue;
                        }
                        stats.fast();
                    } catch(IOException | ClassNotFoundException | ClassCastException e) {}
                }
            } catch (Exception e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    private void register(ObjectOutputStream out, ObjectInputStream in) {
        Object response = null;
        boolean registered = false;
        do {
            String nickname = getName(), password = "1234567890";
            try {
                out.writeObject(new Request(Command.chid, new String[]{nickname, password}));
                response = in.readObject();
                if (response instanceof String) {
                    String res = (String)response;
                    if ("nickname accepted".equals(res)) {
                        registered = true;
                    }
                }
            } catch (ClassNotFoundException | IOException e) {}
        } while (!registered);
    }
}
